import { Card, Button, Form, Input, Checkbox, message } from 'antd'
import { useHistory, useLocation } from 'react-router-dom'
import { login } from '@/store/actions'
import { useDispatch } from 'react-redux'
import logo from '@/assets/logo.png'
import './index.scss'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // 表单验证结束
  const onFinish = async (values) => {
    try {
      // 更新token状态
      await dispatch(login({ mobile: values.mobile, code: values.code }))
      // 全局提示，1s后跳转首页
      message.success('登录成功', 1, () => {
        // 如果是重定向到的登录界面，直接返回要访问的页面
        // 如果不是，默认进入首页/home
        console.log(location.state?.from);
        history.replace(location.state?.from ?? '/home')
      })
    } catch (e) {
      if (!e.response) {
        message.warning('请求超时')
      } else {
        message.warning(e.response.data.message)
      }
    }
  }
  return (
    <div className="login">
      <Card
        className="login-container"
        bordered={false}
        bodyStyle={{
          padding: 20,
        }}
      >
        <img src={logo} alt="" />
        <Form
          size="large"
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: '手机号不能为空',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
              {
                len: 6,
                message: '验证码六个字符',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input placeholder="请输入验证码" maxLength={6} />
          </Form.Item>
          <Form.Item name="agree" valuePropName="checked">
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
